package CellEngine;
import java.net.*;
import java.io.*;

public class ServerClientSocket extends Thread
{
    private Socket socket;
    private boolean authenticated = false;
    private String ip;
    private InputStream inputStream;
    private OutputStream outputStream;
    private boolean active;
    public final int id;
    
	public ServerClientSocket(Socket socket, int id)
	{
		this.id = id;
		ip = ((InetSocketAddress)socket.getLocalSocketAddress()).getAddress().getHostAddress();
		this.socket = socket;
	}
	
	public void run()
	{
		try
		{
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			boolean clientConnected = false, clientAuthed = true;
			int inputChar;
            while((inputChar = inputStream.read()) != -1 && active && connectionAlive())
            {
            	// "real" clients identify themselves by sending a 0x01 byte.
            	// If a client wants information about the server in an XML format, it should send a 0x00 byte.
            	// If anything else is sent to the server, it will print out a human-readable copy of the server stats
            	if(inputChar == 1)
            	{
            		if(Server.net.passwordEnabled())
            			sendChar(1);
            		else
            			sendChar(0);
            	}
            	else if(inputChar == 0)
            	{
            		sendString("<Server>" +
            				"<passwordEnabled>" + Server.net.passwordEnabled() + "</passwordEnabled>" +
            				"</Server>");
            		active = false;
            	}
            	else
            	{
            		sendString("Server details:\r\n");
            		sendString("Password required: " + CellFunc.boolToString(Server.net.passwordEnabled()));
            		active = false;
            	}
            }
            Server.net.connectionMap.remove(id);
            Server.net.connections.remove(this);
            socket.close();
        }
        catch(Exception e) { error(e); }
	}

	public void sendChar(int character) { sendString((char)character + ""); }
	public void sendChar(char character) { sendString(character + ""); }
	public synchronized void sendString(String string)
	{
		try
        {
            for(int i = 0; i < string.length(); i++)
                outputStream.write(string.charAt(i));
            outputStream.flush();
        }
        catch(Exception e) { error(e); }
	}
	
	public String getIPAddress()
	{
		return ip;
	}
	
	public boolean connectionAlive()
	{
        return !socket.isInputShutdown() && !socket.isClosed() && active;
    }
	
	public void error(Exception e)
	{
		Server.log.write("Client socket exception!");
		Server.log.write(" Client ID: " + id);
		Server.log.write(" Client IP: " + ip);
		Server.log.write(" Connection active: " + connectionAlive());
		Server.log.write(" Stacktrace:");
		Server.log.write(" " + e.toString());
		active = false;
	}
}